//
//  PaperItemSubjectiverOptionCell.swift
//  Exam-iOS
//
//  Created by 李胜锋 on 2018/3/9.
//  Copyright © 2018年 李胜锋. All rights reserved.
//

import Foundation
import SnapKit
import Then
import RxCocoa
import RxSwift

class PaperItemSubjectiverOptionCell: UITableViewCell {
    var textView: LSFTextView!
    var answerComplete:((String) -> Void)?
    var disposeBag = DisposeBag()
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        setup()
        bindUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    public func set(_ text: String?) {
        textView.text = text
    }
    
    private func setup() {
        
        self.backgroundColor = .clear
        
        let topLine = UIView().then { (view) in
            view.backgroundColor = Config.default.grayLineViewColor
            
            contentView.addSubview(view)
            view.snp.makeConstraints({ (maker) in
                maker.top.equalTo(10)
                maker.leading.trailing.equalTo(0)
                maker.height.equalTo(1)
            })
        }
        textView = LSFTextView().then({ (tv) in
            tv.placeholder = "请在此输入答案："
            tv.backgroundColor = UIColor.white
            tv.layer.borderWidth = 1
            tv.layer.borderColor = Config.default.grayLineViewColor.cgColor
            
            contentView.addSubview(tv)
            tv.snp.makeConstraints({ (maker) in
                maker.top.equalTo(topLine.snp.bottom).offset(10)
                maker.leading.equalTo(10)
                maker.bottom.trailing.equalTo(-10)
                maker.height.equalTo(100)
            })
        })
    }
    
    
    private func bindUI() {
        
        textView.rx
            .didEndEditing
            .asControlEvent()
            .asObservable()
            .subscribe(onNext: { [weak self] in
                self?.checkInput()
            }).disposed(by: disposeBag)
    }
    
    private func checkInput() {
        if String.lsf_hasValue(textView.text) == false { return }
        let text = textView.text!
        
        answerComplete?(text)
    }
}
